import {listBusiness2, listDealer2, listDealerBusinessType, listBrand2, getDicts, ocrIdCard, ocrCarCard, ocrCarQualified, addService, updateService, getService} from '@/utils/api';
import moment from 'moment';

export default {
    data() {
        return {
            apis: {
                listBusiness2,
                listDealer2,
                listBrand2,
                listDealerBusinessType,
                addService,
                updateService,
                getService,
            },
        };
    },
    methods: {
        async getCommonSelectList({listKey = 'businessSelectList', api = () => {}, resultKey = 'rows', extra = {}}) {
            try {
                let params = {pageSize: 1000, pageNum: 1, ...extra};
                const res = await api({params, custom: {catch: true}});
                this[listKey] = res[resultKey];
                return res[resultKey];
            } catch (error) {
                this[listKey] = [];
                console.error(error);
                return [];
            }
        },

        // 获取字典
        async getDictByKey({dictKey = '', listKey = 'data', apiValueKey = 'data'}) {
            try {
                let response = await getDicts(dictKey, {custom: {catch: true}});
                listKey && (this[listKey] = response[apiValueKey] || []);
            } catch (error) {
                console.log(error);
                listKey && (this[listKey] = []);
            }
        },

        getLifespanParse({value}) {
            try {
                let find = this.lifespanList.find((item) => item.dictLabel == value);
                let year = parseInt(find.dictValue);
                return year;
            } catch (error) {
                return null;
            }
        },
        commonChangeLifespan({formKey, stKey = 'startTime', addKey = 'lifespan', endKey = 'endTime', rule = 'YYYY-MM-DD HH:mm:ss'}) {
            try {
                if (this[formKey][stKey]) {
                    // 在原有的基础上减去一天然后再加上响应的val 年
                    let year = this.getLifespanParse({value: this[formKey][addKey]});
                    this[formKey][endKey] = moment(this[formKey][stKey]).subtract(1, 'days').endOf('day').add(year, 'years').format(rule);
                }
            } catch (e) {
                console.log(e);
            }
        },

        commonStartTimeChange({val, formKey, stKey = 'startTime', endKey = 'endTime', addKey = 'lifespan', rule = 'YYYY-MM-DD HH:mm:ss'}) {
            try {
                if (val) {
                    let year = this.getLifespanParse({value: this[formKey][addKey]});
                    this[formKey][endKey] = moment(this[formKey][stKey]).subtract(1, 'days').endOf('day').add(year, 'years').format(rule);
                }
            } catch (error) {}
        },
        commonEndTimeChange({val, formKey, stKey = 'startTime', endKey = 'endTime', addKey = 'lifespan', rule = 'YYYY-MM-DD HH:mm:ss'}) {
            try {
                if (val) {
                    let year = this.getLifespanParse({value: this[formKey][addKey]});
                    this[formKey][stKey] = moment(this[formKey][endKey]).add(1, 'days').subtract(year, 'years').startOf('day').format(rule);
                }
            } catch (error) {
                console.log(error);
            }
        },

        handleFormPromise() {
            try {
                let formPromises = [];
                for (let i = 0; i < this.checkList.length; i++) {
                    let item = this.checkList[i];
                    if (item == '基础数据') {
                        let basicPromise = new Promise(async (resolve, reject) => {
                            try {
                                await this.$refs['form'].validate();
                                resolve(true);
                            } catch (error) {
                                resolve(false);
                            }
                        });
                        formPromises.push(basicPromise);
                    } else {
                        let find = this.ServiceConfig.dealerBusinessTypes.find((_item) => _item.label == item);
                        if (find) {
                            let servicePromise = new Promise(async (resolve, reject) => {
                                try {
                                    await this.$refs[`serviceModelForm${find.value}`].validate();
                                    resolve(true);
                                } catch (error) {
                                    resolve(false);
                                }
                            });
                            formPromises.push(servicePromise);
                        }
                    }
                }
                return formPromises;
            } catch (error) {
                console.log(error);
                return Promise.resolve([]);
            }
        },

        // 计算购置税
        getPurchaseTax({price}) {
            try {
                return (price / 11.3).toFixed(2);
            } catch (error) {
                return 0;
            }
        },

        async imageUploadChange({val, type}) {
            // 1.先上传身份证，再上传车辆发票 以身份证姓名为准
            // 2.先上传发票，在上传身份证 以身份证姓名为准
            // 3.单独上传车辆发票/身份证都可识别姓名
            try {
                if (Array.isArray(val) && val.length == 0) return;
                let origin = window.location.origin;
                let fileURL = origin + this.globalVar.request.baseURL + val[0].url;
                if (type == 'idCardZ') {
                    // let response = await ocrIdCard({params: {url: 'https://www.mengmakeji.cn/shop-img/徐.jpg'}, custom: {catch: true}});
                    let response = await ocrIdCard({params: {url: fileURL}, custom: {catch: true}});
                    let body = JSON.parse(response.data.body.Data);
                    this.form.customerName = body.data.face.data.name;
                    this.form.certificateNumber = body.data.face.data.idNumber;
                    this.form.address = body.data.face.data.address;
                    return;
                }
                if (type == 'vehicleInvoice') {
                    // 车辆发票 不含营业执照
                    // let response = await ocrCarCard({params: {url: 'https://www.mengmakeji.cn/shop-img/car2.jpg'}, custom: {catch: true}});
                    // let response = await ocrCarCard({params: {url: 'http://yarningbo.cn:81/Image/cql-fp.png'}, custom: {catch: true}});
                    let response = await ocrCarCard({params: {url: fileURL}, custom: {catch: true}});
                    let body = JSON.parse(response.data.body.Data);
                    this.form.certificateType = '身份证';
                    if (!this.form.customerName) {
                        this.form.customerName = body.data.purchaserName;
                    }
                    this.form.frameNumber = body.data.vinCode;
                    this.form.engineNo = body.data.engineNumber;
                    let [a, b, c, d] = body.data.brandMode.match(/^(.*?)(牌)(.*)$/);
                    this.form.brandName = b;
                    this.form.modelName = d;
                    this.form.certificateNumber = body.data.purchaserTaxNumber;
                    this.form.peopleNumer = body.data.passengerLimitNumber ? body.data.passengerLimitNumber : '5';
                    this.form.carMoney = body.data.invoiceAmount;
                    this.form.registrationDate = moment(body.data.invoiceDate).format('YYYY-MM-DD HH:mm:ss');
                    //  非油车 不是油车的话购置税不需要计算,默认为0, 只要包含 电 或者 混 就是非油车
                    // let isNonOil = body.data.vehicleType == '纯电动轿车' || body.data.vehicleType == '插电式混合动力轿车';
                    let isNonOil = body.data.vehicleType.indexOf('电') > -1 || body.data.vehicleType.indexOf('混') > -1;
                    this.form.carryPassenger = isNonOil ? '0' : this.getPurchaseTax({price: +body.data.invoiceAmount});
                    return;
                }
                if (type == 'carQualified') {
                    // let response = await ocrCarQualified({params: {url: 'https://www.mengmakeji.cn/shop-img/hg.jpg'}, custom: {catch: true}});
                    // let response = await ocrCarQualified({params: {url: 'http://yarningbo.cn:81/Image/hg.png'}, custom: {catch: true}});
                    let response = await ocrCarQualified({params: {url: fileURL}, custom: {catch: true}});
                    let body = JSON.parse(response.data.body.Data);
                    this.form.frameNumber = body.data.vinCode;
                    this.form.engineNo = body.data.engineNumber;
                    // 先识别车辆发票,如果车辆发票没有识别到品牌型号,再识别合格证
                    if (!this.form.brandName) {
                        this.form.brandName = body.data.vehicleBrand.replace('牌', '');
                    }
                    this.form.modelName = body.data.vehicleModel;
                    return;
                }
            } catch (error) {
                console.log(error);
                this.$u.toast('OCR识别失败');
            }
        },
    },
};
